;; =============
;; EXERCISE 2.05
;; =============

;; Show that we can represent pairs of nonnegative integers using only
;; numbers and arithmetic operations if we represent the pair a and b
;; as the integer that is the product 2^a*3^b. Give the corresponding
;; definitions of the procedures cons, car, and cdr.

;; =============
;; SOLUTION 2.05
;; =============

(define (cons a b)
  (* (expt 2 a)
     (expt 3 b)))

(define (count-remainder-0-divisions num divisor)
  (define (iter remaining-product divisions-counter)
    (cond [(= remaining-product 0)
           divisions-counter]
          [(= 0 (remainder remaining-product divisor))
           (iter (/ remaining-product divisor) (+ divisions-counter 1))]
          [else
           divisions-counter]))
  (iter num 0))

(define (car p)
  (count-remainder-0-divisions p 2))

(define (cdr p)
  (count-remainder-0-divisions p 3))

;; =====
;; TESTS
;; =====

(use-modules (srfi srfi-64))

(test-begin "test-cons-car-cdr")
(test-group
 "test-cons-car-cdr"
 (test-equal
     5 (car (cons 5 4)))
 (test-equal
     4 (cdr (cons 5 4))))

(test-end "test-cons-car-cdr")
